package com.laborer.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.laborer.entity.Task;
import com.laborer.entity.User;
import com.laborer.model.result.Result;
import com.laborer.service.ITaskService;
import com.laborer.service.IUserService;
import com.laborer.utils.TaskStateMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.UUID;

/**
 * @Author: zhangzhe
 * @Date:   2021-06-08
 * @Version: V1.0
 */
@Controller
@RequestMapping("/task")
@Slf4j
public class TaskController{
	private final  String PREFIX="assignmentTask";
	@Autowired
	private ITaskService iTaskService;
	@Autowired
	private IUserService iUserService;

	@RequestMapping("")
	public String task(){
		return PREFIX+"/assignmentTask";
	}
	@RequestMapping("/list")
	@ResponseBody
	public Result list(){
		return this.userByTask(null);
	}

	@ResponseBody
	@RequestMapping("/userByTask")
	public Result userByTask(User user){
		Result result=new Result();
		QueryWrapper<Task> queryTask=new QueryWrapper<>();
		if(user!=null){
			queryTask.eq("user_id",user.getId());
		}
		List<Task> list = iTaskService.list(queryTask);
		if(list!=null && list.size()>0){
			for(int i=0;i<list.size();i++){
				Task task = list.get(i);
				task.setTaskState(TaskStateMap.map.get(task.getTaskState()));
				User byId = iUserService.getById(task.getUserId());
				task.setUserId(byId.getUserName());
			}
		}

		result.success(list,10,1);
		return result;
	}
	@RequestMapping("/detail")
	public String detail(User user, Model model){
		model.addAttribute("userId",user.getId());
		return PREFIX + "/detail";
	}

	@RequestMapping("/add")
	public String add(Model model) {
		List<User> list = iUserService.list(null);
		model.addAttribute("users",list);
		return PREFIX+"/assignmentTask_add";
	}

	@RequestMapping("/save")
	@ResponseBody
	public Result save(Task task){
		Result result=new Result();
		UUID uuid = UUID.randomUUID();
		String id = uuid.toString().replace("-", "");
		task.setId(id);
		task.setIsDel(0);
		boolean save = iTaskService.save(task);
		if(save){
			result.setCode(0);
			result.setSuccess(true);
			return result;
		}

		result.error("新增异常");

		return result;
	}
//	@RequestMapping("/detail")
//	public Result view(Task task){
//		Result result=new Result();
//		Task byId = iTaskService.getById(task.getId());
//		result.success(byId,10,1);
//		return result;
//	}

	@RequestMapping("/edit")
	public void edit(Task task){
		iTaskService.updateById(task);
	}
}
